package login.logic;

import java.io.IOException;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.Channel;
import lion.lan.ILanIoExecutor;
import lion.lan.Netty4LanServer;
import lion.netty4.message.RequestMessage;
import lion.netty4.message.SendToMessage;
import login.LoginServer;
import login.dao.LogIdfaDao;
import login.msg.SendAnnounce2GmMessage;

public class LoginLanServerManager implements ILanIoExecutor {

	private static Logger logger = LoggerFactory.getLogger(LoginLanServerManager.class);

	private Netty4LanServer lanServer;

	static class SingletonHolder {
		static LoginLanServerManager instance = new LoginLanServerManager();
	}

	public static LoginLanServerManager getInstance() {
		return SingletonHolder.instance;
	}

	private LoginLanServerManager() {
	}

	public void startServer(int port) {
		try {
			lanServer = new Netty4LanServer(port);
			lanServer.run(Runtime.getRuntime().availableProcessors(), this, LoginServer.executorService);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void shutdown() {
		if (lanServer != null) {
			lanServer.shutdown();
		}
	}

	@Override
	public void execute(final Channel channel, RequestMessage requestMessage) throws IOException {
		// ip判断
		Set<String> allowIpSet = LoginServer.getInstance().getLoginServerConfig().getLanAllowIps();
		if (channel.remoteAddress() != null) {
			String ipStr = channel.remoteAddress().toString();
			String aIp = StringUtils.split(ipStr, ":")[0].substring(1);
			if (!allowIpSet.contains(aIp)) {
				logger.warn("not valid ip lan request,ipAddr={}", ipStr);
				return;
			}
		}
		switch (requestMessage.getMsgCode()) {
		case 10039:// 请求公告内容
			SendAnnounce2GmMessage activityOneMsg = new SendAnnounce2GmMessage(channel.alloc());
			activityOneMsg.setVal(LoginServer.getInstance().getLoginServerConfig().getAnnouncement());
			channel.writeAndFlush(activityOneMsg);
			break;
		case 10041:// 编辑公告
			String announcementContent = requestMessage.readString();
			LoginServer.getInstance().getLoginServerConfig().setAnnouncement(announcementContent);
			break;
		case 10047:
			String queryDate = requestMessage.readString();
			int count = LogIdfaDao.getInstance().getUniqueIdfaCount(queryDate);
			SendToMessage retMsg = new SendToMessage(channel.alloc(), 10048);
			retMsg.writeInt(count);
			channel.writeAndFlush(retMsg);
			break;
		case 11001:
			long randOrderId = requestMessage.readLong();
			int serverId = requestMessage.readInt();
			String openId = requestMessage.readString();
			int productId = requestMessage.readInt();
			logger.info("xiao7 add pay info,randOrderId={},serverId={},openId={},productId={}", randOrderId, serverId,
					openId, productId);
			Xiao7PayListManager.getInstance().addPayInfo(randOrderId, openId, serverId, productId);
			break;
		default:
			break;
		}
	}

}
